package com.example.videoplayer.service.impl;

import com.example.videoplayer.model.User;
import com.example.videoplayer.repository.UserRepository;
import com.example.videoplayer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Mono<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public Mono<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public Flux<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public Mono<User> save(User user) {
        // 如果是新用户，加密密码
        if (user.getId() == null && user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return userRepository.save(user);
    }

    @Override
    public Mono<Void> deleteById(Long id) {
        return userRepository.deleteById(id);
    }

    @Override
    public Mono<User> updatePassword(Long id, String newPassword) {
        return userRepository.findById(id)
                .flatMap(user -> {
                    String encodedPassword = passwordEncoder.encode(newPassword);
                    return userRepository.updatePassword(id, encodedPassword)
                            .then(Mono.just(user));
                });
    }
} 